package com.hjq.fcloud.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup.GONE
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.internal.LinkedTreeMap
import com.hjq.bar.TitleBar
import com.hjq.fcloud.R
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.config.Config
import com.hjq.fcloud.config.SystemSet
import com.hjq.fcloud.http.api.GetListDataApi
import com.hjq.fcloud.http.api.GetListJsonApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.ktx.ViewKtx.setVisibility
import com.hjq.fcloud.jump.CommonJumpBean
import com.hjq.fcloud.model.CommonListSubModel
import com.hjq.fcloud.jump.CommonJump
import com.hjq.fcloud.other.SignStatusHelper
import com.hjq.fcloud.presenter.CommonListPresenter
import com.hjq.fcloud.utils.AppConfigUtils
import com.hjq.fcloud.utils.DrawableUtils
import com.hjq.fcloud.utils.EmptyViewUtil
import com.hjq.fcloud.utils.Logger
import com.hjq.fcloud.widget.ClearTextView
import com.hjq.fcloud.widget.StatusLayout
import com.hjq.http.EasyHttp
import com.hjq.http.body.JsonBody
import com.hjq.http.listener.HttpCallback
import com.hjq.toast.ToastUtils
import com.hjq.widget.layout.WrapRecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.activity_common_list.addIv
import kotlinx.android.synthetic.main.activity_common_list.stateLayout
import okhttp3.Call
import java.util.*

/**
 * 公共列表
 */
open class CommonListActivity : AppActivity(), OnRefreshLoadMoreListener {

    companion object {
        const val INTENT_COMMON_LIST_KEY_ID = "intent_common_list_key_id"
        const val INTENT_COMMON_LIST_KEY_BIZ_CODE = "intent_common_list_key_biz_code"

        fun launcher(
            context: Context,
            id: String, bizCode: String?
        ) {
            if (TextUtils.isEmpty(bizCode)) {
                ToastUtils.show("biz_code不能为空")
                return
            }
            var intent = Intent(context, CommonListActivity::class.java)
            intent.putExtra(INTENT_COMMON_LIST_KEY_ID, id)
            intent.putExtra(INTENT_COMMON_LIST_KEY_BIZ_CODE, bizCode)
            context.startActivity(intent)
        }

        /**
         * 刷新列表，从详情跳转过来的
         */
        fun refershList(context: Context) {
            var intent = Intent(context, CommonListActivity::class.java)
            context.startActivity(intent)
        }
    }


    protected var mTitleBar: TitleBar? = null
    private var mStatusLayout: StatusLayout? = null
    private var mRefreshLayout: SmartRefreshLayout? = null
    protected var mRecyclerView: WrapRecyclerView? = null
    protected open var mAdapter: BaseQuickAdapter<Any, BaseViewHolder>? = null
    private var queryTv: ClearTextView? = null

    //调用接口需要传
    private val mIntentMenuId by lazy { getString(INTENT_COMMON_LIST_KEY_ID) }

    //区分跳转详情
    private val mBizCode by lazy { getString(INTENT_COMMON_LIST_KEY_BIZ_CODE) }

    protected var templeJson: List<GetListJsonApi.DataDTO.JsonDTO>? = null

    private var mQueryOrderMap: HashMap<String, String> = HashMap<String, String>()

    protected open var mQueryOrderMapValue: HashMap<String, String> = HashMap<String, String>()

    var mCurrentPage: Int = 1

    private var total: Int? = 1

    var mList: List<Any>? = null

    private var mTitle: String? = "查询"

    private var mInfo: GetListJsonApi.DataDTO.InfoDTO? = null

    private var showSearch: Boolean = false

    private val mPresenter: CommonListPresenter by lazy { CommonListPresenter() }
    //选中的需求
    val selectProjectBean by lazy { AppConfigUtils.getSelectProjectItemBean() }

    override fun getLayoutId(): Int {
        return R.layout.activity_common_list
    }

    override fun initView() {
        queryTv = findViewById(R.id.queryTv)
        mStatusLayout = findViewById(R.id.hl_status_hint)
        mTitleBar = findViewById(R.id.id_title_bar)
        queryTv?.setOnClickListener(View.OnClickListener {
            if (templeJson != null && mQueryOrderMap != null) {
                var intent = Intent(this, CommonListQueryActivity::class.java)
                intent.putExtra(CommonListQueryActivity.INTENT_KEY_TITLE, mTitle)
                intent.putExtra(CommonListQueryActivity.INTENT_KEY_QUERY_MAP, mQueryOrderMap!!)
                intent.putExtra(
                    CommonListQueryActivity.INTENT_KEY_QUERY_MAP_VALUE,
                    mQueryOrderMapValue!!
                )
                intent.putExtra(
                    CommonListQueryActivity.INTENT_KEY_SHOW_JSON_STR,
                    JSON.toJSONString(templeJson)
                )
                startActivityForResult(
                    intent,
                    object : OnActivityCallback {
                        override fun onActivityResult(resultCode: Int, data: Intent?) {
                            if (resultCode == RESULT_OK) {
                                mCurrentPage = 1
                                mQueryOrderMap =
                                    data?.extras?.getSerializable(CommonListQueryActivity.INTENT_KEY_QUERY_MAP) as HashMap<String, String>
                                mQueryOrderMapValue =
                                    data?.extras?.getSerializable(CommonListQueryActivity.INTENT_KEY_QUERY_MAP_VALUE) as HashMap<String, String>
                                getServerListData()
                            }
                        }
                    })
            }
        })
        queryTv?.setOnClearClickLisener {
            clearQueryMap()
            mRefreshLayout?.autoRefresh()
        }

        mRefreshLayout = findViewById(R.id.rl_status_refresh)
        mRecyclerView = findViewById(R.id.id_list_rv)
        mRecyclerView?.layoutManager = LinearLayoutManager(context)

        mRefreshLayout?.setOnRefreshLoadMoreListener(this)

        if(mBizCode?.equals(CommonJump.COMMON_JUMP_CODE_IMAGE_UPLOAD) == true){
            var hasPermission = SystemSet.getMenuPermission(mBizCode)?.add == 1
            if(hasPermission){
                addIv.setVisibility(true)
                addIv.setOnClickListener {
                    var jumpBean = CommonJumpBean()
                    jumpBean.setBizCode(mBizCode)
                    CommonJump.commonJump(this@CommonListActivity,jumpBean)
                }
            }
        }
    }

    override fun initData() {
        Logger.i("--->>>getServerTemple mIntentMenuId:"+mIntentMenuId)
        mCurrentPage = 1
        getServerTemple()
    }


    open fun getServerTemple() {
        showAppLoading()
        EasyHttp.post(this)
            .api(
                GetListJsonApi()
                    .setMenu_id(mIntentMenuId)
                    .setFnc_id(selectProjectBean?.selectFncItemBean?.id)
            )
            .request(object : HttpCallback<HttpData<GetListJsonApi.DataDTO>>(this) {
                override fun onStart(call: Call?) {}
                override fun onSucceed(data: HttpData<GetListJsonApi.DataDTO>?) {
                    try {
                        data?.let {
                            var info = data.getData()?.info
                            mInfo = info
                            mTitle = info?.title
                            mTitleBar?.setTitle(mTitle)

                            templeJson = data.getData()?.json
                            if (templeJson != null && templeJson!!.size > 0) {
                                handlerQueryMap()

                                if (showSearch) {
                                    queryTv?.visibility = View.VISIBLE
                                } else {
                                    queryTv?.visibility = View.GONE
                                }

                                getServerListData();
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
//                            toast(R.string.string_data_parse_error)
                        Log.e("TAG", "GetListJsonApi string_data_parse_error")
                        getServerListData();
                    }
                }

                override fun onEnd(call: Call?) {
                    super.onEnd(call)
                    mRefreshLayout!!.finishRefresh()
                }
            })
    }

    private fun handlerQueryMap() {
        mQueryOrderMap = getQueryOrderMap()
    }

    open fun getServerListData(isLoadMore: Boolean = false) {
        //这里动态拼接参数
        var buildParmsJson = JSONObject()
        buildParmsJson.put("menu_id", mIntentMenuId)
        buildParmsJson.put("fnc_id",selectProjectBean?.selectFncItemBean?.id)
//        buildParmsJson.put("biz_code",CommonJumpBean.parseBizCode(mBizCode))
        mQueryOrderMap?.put(Config.SERVER_LIST_KEY_PAGE, mCurrentPage.toString())
        mQueryOrderMap?.put(Config.SERVER_LIST_KEY_LIMIT, Config.SERVER_LIST_LIMIT.toString())
        buildParmsJson.put("data", mQueryOrderMap)

        EasyHttp.post(this)
            .api(GetListDataApi())
            .body(JsonBody(buildParmsJson))
            .request(object : HttpCallback<HttpData<GetListDataApi.DataDTO>>(this) {
                override fun onSucceed(data: HttpData<GetListDataApi.DataDTO>) {
                    resetList(isLoadMore)

                    total = data.getData()?.total
                    mList = data.getData()?.records
                    mAdapter?.data?.addAll(mList!!)

                    setAdapter()

                    setQueryViewData()
                }

                private fun resetList(loadMore: Boolean) {
                    if (!loadMore) {
                        mAdapter?.data?.clear()
                    }
                }

                override fun onStart(call: Call?) {
                }

                override fun onEnd(call: Call?) {
                    mRefreshLayout!!.finishRefresh()
                    mRefreshLayout!!.finishLoadMore()

                    showAppContent()
                }
            })

    }

    private fun setQueryViewData() {
        var queryCondition =
            mPresenter.getQueryCondition(templeJson, mQueryOrderMap, mQueryOrderMapValue)
        queryTv?.setText(queryCondition)
    }

    fun setAdapter() {
        if (mAdapter == null) {
            mAdapter =
                object : BaseQuickAdapter<Any, BaseViewHolder>(R.layout.item_common_list, mList) {
                    override fun convert(helper: BaseViewHolder, item: Any) {
                        var obj: LinkedTreeMap<String, Any> = item as LinkedTreeMap<String, Any>

                        var subList = getSubList(obj)

                        addChildView(helper, subList, obj)

                        handlerOtherView(helper, obj)
                    }

                    private fun addChildView(
                        helper: BaseViewHolder,
                        subList: MutableList<CommonListSubModel>,
                        obj: LinkedTreeMap<String, Any>
                    ) {
                        var fatherView: LinearLayout = helper.getView(R.id.id_common_list_ll)
                        fatherView.removeAllViews()

                        for (pos in 0..subList.size - 1) {
                            var item = subList.get(pos)

                            var subItemView =
                                layoutInflater.inflate(R.layout.item_common_item_sub_list, null)
                            fatherView.addView(subItemView)

                            var leftView = subItemView.findViewById<TextView>(R.id.id_left_tv)
                            leftView.setText(item.leftStr + "：")
                            var rightTv = subItemView.findViewById<TextView>(R.id.id_right_tv)
                            rightTv.setText(item.rightStr)

                            //签约状态
                            var statusNameTv = subItemView.findViewById<TextView>(R.id.statusNameTv)
                            statusNameTv.setVisibility(false)

                            //签约
                            var statusFlowTv = subItemView.findViewById<TextView>(R.id.statusFlowTv)
                            statusFlowTv.setVisibility(false)

                            //第一个位置设置大标题显示
                            if (pos == 0) {
                                showBigTitle(leftView, rightTv, statusNameTv, obj)
                            } else {
                                rightTv.setTextColor(item.rightStrColorResId)
                                if(pos == subList.size - 1){
                                    var hasPermission = (SystemSet.getMenuPermission(mBizCode)?.edit == 1)
                                    if(hasPermission){
                                        SignStatusHelper.setRightStatusFlowStyle(statusFlowTv, obj,mIntentMenuId,{
                                            jumpDetail(obj, true)
                                        })
                                    }
                                }
                            }
                        }
                    }

                    /**
                     * 显示大标题
                     */
                    private fun showBigTitle(
                        leftView: TextView,
                        rightTv: TextView,
                        statusNameTv: TextView,
                        obj: LinkedTreeMap<String, Any>
                    ) {
                        //左边按钮隐藏
                        leftView.visibility = GONE

                        //右边按钮样式设置
                        rightTv.setTextColor(resources.getColor(R.color.common_color_blue))
                        rightTv.setTextSize(
                            TypedValue.COMPLEX_UNIT_PX,
                            resources.getDimension(R.dimen.sp_16)
                        )
                        rightTv.paint.isFakeBoldText = true

                        setRightStatusNameStyle(obj, statusNameTv)
                    }
                }
            //recycleview中设置emptyview
            mAdapter?.setEmptyView(EmptyViewUtil.getEmptyView(context, null))
            mRecyclerView?.setAdapter(mAdapter)
            mAdapter?.setOnItemClickListener(object : BaseQuickAdapter.OnItemClickListener {
                override fun onItemClick(
                    adapter: BaseQuickAdapter<*, *>?,
                    view: View?,
                    position: Int
                ) {
                    try {
                        var jsonItem = mAdapter?.data?.get(position)
                        var item: LinkedTreeMap<String, Any> = jsonItem as LinkedTreeMap<String, Any>
                        jumpDetail(item)
                    }catch (e:Exception){
                        e.printStackTrace()
                        showToast("数据异常")
                    }
                }
            })
        } else {
            mAdapter?.notifyDataSetChanged()
        }

        handlerCanMore();
    }

    /**
     * 设置签约状态样式
     */
    private fun setRightStatusNameStyle(
        obj: LinkedTreeMap<String, Any>,
        statusNameTv: TextView
    ) {
        //签约状态
        var statusName = obj.get("status_name")?.toString()
        if (!TextUtils.isEmpty(statusName)) {
            var statusNameColor = obj.get("color")?.toString()
            if (!TextUtils.isEmpty(statusNameColor)) {
                DrawableUtils.setTextStyleByStyle(statusNameTv, statusName!!, statusNameColor!!)
            }
        }
    }

    open fun handlerOtherView(helper: BaseViewHolder, obj: LinkedTreeMap<String, Any>) {}

    open fun jumpDetail(item: LinkedTreeMap<String, Any>, startSign: Boolean = false) {
        var jumpBean = CommonJumpBean()
        jumpBean.isStartSign = startSign
        jumpBean.bizId = item.get("list_id")?.toString()
        jumpBean.setBizCode(mBizCode)
        CommonJump.commonJump(this@CommonListActivity, jumpBean)
    }

    fun handlerCanMore() {
        if (mAdapter?.data?.size!! < total!!) {
            mRefreshLayout?.setEnableLoadMore(true)
        } else {
            mRefreshLayout?.setEnableLoadMore(false)
        }
    }

    /**
     * 得到subList
     */
    open fun getSubList(obj: LinkedTreeMap<String, Any>): MutableList<CommonListSubModel> {
        var subList = mutableListOf<CommonListSubModel>()
        for (index in 0..templeJson?.size!! - 1) {
            var temple: GetListJsonApi.DataDTO.JsonDTO = templeJson!!.get(index)

            if (temple != null) {
                //hideInTable=0 才在列表显示
                if (temple.hideInTable == 0) {
                    var leftStr = temple.title
                    var href = temple.href
                    var valueType = temple.valueType

                    var rightStr = getRightStr(obj, temple)

                    var rightStrColorResId = getRightTvColor(temple)

                    var subModel = CommonListSubModel(
                        leftStr,
                        rightStr,
                        rightStrColorResId,
                        href,
                        temple
                    )
                    subList.add(subModel)
                }
            }
        }
        return subList
    }

    private fun getRightStr(
        obj: LinkedTreeMap<String, Any>,
        temple: GetListJsonApi.DataDTO.JsonDTO
    ): String {
        var rightStr = obj.get(temple.dataIndex).toString()
        //过滤null
        rightStr = if (rightStr.equals("null")) "" else rightStr
        if(temple.dataIndex.equals("percentage")){
            //如果是进度，则加一个%在末尾
            rightStr += "%"
        }
        return rightStr
    }

    private fun getRightTvColor(
        temple: GetListJsonApi.DataDTO.JsonDTO
    ): Int {
        var defaultColor = getDetaultTvColor()

        //消息内容标记颜色
        if (temple.dataIndex.equals("msg_content")) {
            return resources.getColor(R.color.common_color)
        }

        return defaultColor
    }

    private fun getDetaultTvColor() = resources.getColor(R.color.common_text_color_333)


    /**
     * 通过模板得到查询条件用于筛选查询，默认值都为空字符串
     */
    open fun getQueryOrderMap(): HashMap<String, String> {
        var queryOrderMap = HashMap<String, String>()
        for (index in 0..templeJson?.size!! - 1) {
            var temple: GetListJsonApi.DataDTO.JsonDTO = templeJson!!.get(index)

            if (temple != null) {
                //hideInTable=0 才在列表显示
                if (temple.hideInSearch == 0) {
                    //默认值都为空字符串
                    queryOrderMap.put(temple.dataIndex, "")

                    showSearch = true
                }
            }
        }
        return queryOrderMap
    }

    override fun getStateLayout(): View? {
        return stateLayout
    }


    /**
     * [OnRefreshLoadMoreListener]
     */
    override fun onRefresh(refreshLayout: RefreshLayout) {
        refresh()
    }

    private fun refresh() {
        mCurrentPage = 1
        getServerListData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mCurrentPage++
        getServerListData(true)
    }

    override fun onDestroy() {
        super.onDestroy()
        clearQueryMap()
    }

    private fun clearQueryMap() {
        mQueryOrderMap?.clear()
        mQueryOrderMapValue.clear()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        var bundle = getBundle()
        if(bundle != null){
            outState.putAll(bundle)
        }
        Logger.i("--->>>onSaveInstanceState outState:"+getBundle()?.getString(INTENT_COMMON_LIST_KEY_ID))
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        intent.putExtras(savedInstanceState)
        Logger.i("--->>>onRestoreInstanceState savedInstanceState:"+getBundle()?.getString(INTENT_COMMON_LIST_KEY_ID))
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Logger.i("--->>>onNewIntent refresh")
        refresh()
    }
}